import mongoose, { Schema, Document } from 'mongoose';

/**
 * 设置类型
 */
export enum SettingsType {
  USER = 'user',
  SYSTEM = 'system',
  INTEGRATION = 'integration'
}

/**
 * 通知渠道配置
 */
export interface NotificationChannel {
  type: 'email' | 'slack' | 'dingtalk' | 'webhook';
  enabled: boolean;
  config: {
    [key: string]: any;
  };
}

/**
 * 集成配置
 */
export interface IntegrationConfig {
  prometheus?: {
    url: string;
    enabled: boolean;
  };
  grafana?: {
    url: string;
    enabled: boolean;
  };
  alertmanager?: {
    url: string;
    enabled: boolean;
  };
  openai?: {
    apiKey: string;
    model: string;
    enabled: boolean;
  };
}

/**
 * 用户偏好设置
 */
export interface UserPreferences {
  theme: 'light' | 'dark' | 'auto';
  language: 'en' | 'zh' | 'auto';
  timezone: string;
  dateFormat: string;
  timeFormat: '12h' | '24h';
  notifications: {
    email: boolean;
    browser: boolean;
    sound: boolean;
  };
  dashboard: {
    layout: string[];
    defaultView: string;
  };
}

/**
 * 系统配置
 */
export interface SystemConfig {
  siteName: string;
  siteUrl: string;
  adminEmail: string;
  alertRetentionDays: number;
  ticketRetentionDays: number;
  enableAIAnalysis: boolean;
  enableAutoCreateTicket: boolean;
  slaEnabled: boolean;
  slaPolicies: {
    critical: number;  // hours
    high: number;
    medium: number;
    low: number;
  };
  maintenanceMode: boolean;
  maintenanceMessage: string;
}

/**
 * Settings Document Interface
 */
export interface ISettings extends Document {
  _id: mongoose.Types.ObjectId;
  type: SettingsType;
  userId?: string;  // For user settings
  key: string;
  value: any;
  metadata?: {
    description?: string;
    category?: string;
    updatedBy?: string;
  };
  createdAt: Date;
  updatedAt: Date;
}

/**
 * Settings Schema
 */
const SettingsSchema: Schema = new Schema(
  {
    type: {
      type: String,
      required: true,
      enum: Object.values(SettingsType),
      index: true
    },
    userId: {
      type: String,
      index: true
    },
    key: {
      type: String,
      required: true,
      index: true
    },
    value: {
      type: Schema.Types.Mixed,
      required: true
    },
    metadata: {
      description: String,
      category: String,
      updatedBy: String
    }
  },
  {
    timestamps: true,
    collection: 'settings'
  }
);

// 复合索引确保唯一性
SettingsSchema.index({ type: 1, userId: 1, key: 1 }, { unique: true });

/**
 * Static Methods
 */
SettingsSchema.statics.getUserSettings = async function(userId: string): Promise<ISettings[]> {
  return this.find({ type: SettingsType.USER, userId });
};

SettingsSchema.statics.getSystemSettings = async function(): Promise<ISettings[]> {
  return this.find({ type: SettingsType.SYSTEM });
};

SettingsSchema.statics.getIntegrationSettings = async function(): Promise<ISettings[]> {
  return this.find({ type: SettingsType.INTEGRATION });
};

SettingsSchema.statics.setSetting = async function(
  type: SettingsType,
  key: string,
  value: any,
  userId?: string,
  updatedBy?: string
): Promise<ISettings> {
  const filter: any = { type, key };
  if (userId) filter.userId = userId;

  return this.findOneAndUpdate(
    filter,
    {
      value,
      'metadata.updatedBy': updatedBy,
      'metadata.category': key.split('.')[0]  // Extract category from key
    },
    { upsert: true, new: true }
  );
};

export default mongoose.model<ISettings>('Settings', SettingsSchema);
